//
//  SaUserDataCenter.m
//  saas
//
//  Created by fangyibao on 2019/10/15.
//  Copyright © 2019 fangmao. All rights reserved.
//

#import "SaUserDataCenter.h"
#import "SaDBManager.h"
#import <FMDB.h>
 NSString *const Sa_UserData_Table = @"t_userdata";
static SaUserDataCenter *_data;
@interface SaUserDataCenter ()
@property (nonatomic, copy) SaDBManager *dbManager;
@end
@implementation SaUserDataCenter

+(instancetype)shareIntance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _data = [self new];
    });
    return _data;
}
- (instancetype)init{
    if (self = [super init]) {
        [self _creatUserDataTable];
        [self _queryNativeUserData];
    }
    return self;
}
- (void)_queryNativeUserData{
    NSString *sql = [NSString stringWithFormat:@"SELECT MAX(id) AS Id, accessToken, userId, islogin,expiresTime,refreshToken FROM %@;", Sa_UserData_Table];
    FMResultSet *res = [self.dbManager queryDataWithTableName:Sa_UserData_Table sql:sql];
    while ([res next]) {
        self.accessToken = [res stringForColumn:@"accessToken"];
        self.userId = [res intForColumn:@"userId"];
        self.isLogin = [res intForColumn:@"islogin"]==1?YES:NO;
        self.expiresTime = [res stringForColumn:@"expiresTime"];
        self.refreshToken = [res stringForColumn:@"refreshToken"];
    }
}
- (BOOL)update{
    return NO;
}
- (BOOL)save{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (accessToken, userId, islogin,expiresTime,refreshToken) VALUES(%@, %@, %@, %@, %@)", Sa_UserData_Table, self.accessToken, @(self.userId), @(self.isLogin?1:0), self.expiresTime,self.refreshToken];
    return [self.dbManager insertDataWithTableName:Sa_UserData_Table sql:sql];
    
}
- (BOOL)_creatUserDataTable{
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT, accessToken TEXT, userId INTEGER,islogin INTEGER,expiresTime TEXT, refreshToken TEXT);", Sa_UserData_Table];
    return [self.dbManager creatTableWithName:Sa_UserData_Table sql:sql];
}
- (SaDBManager *)dbManager{
    if(!_dbManager){
        _dbManager = [SaDBManager shareManager];
    }
    return _dbManager;
}
@end
